import React from 'react'
import { useReducer } from 'react'

// 顶层组件App/index.js <MyContext.Provider value={createReducer()}>
// 子孙组件TestUseReducer const { dispatch, state } = useContext(MyContext)
const MyContext = React.createContext({})

// useReducer的state,dispatch 传到APP <MyContext.Provider value={createReducer()}>
const createReducer = () => {
  const initState = {
    foreground: "#ffffff",
    background: "#222222",
    appName: 'reactHooks'
  };
  // 这里只是为了演示 
  // 通过Provider及createContext跨层级发送接受useReducer产生的state, dispatch, 从而实现state跨组件共享
  // useReducer主要还是用于单组件复杂state变化的情况 以替代useState
  const [state, dispatch] = useReducer((state, action) => {
    if(action.type === 'changeColorAndAppName') {
      return {
        ...state,
        foreground: "#fac",
        appName: state.appName.split('').reverse().join('')
      }
    }
  }, initState)
  return { state, dispatch }
}

export {
  MyContext,
  createReducer
}